<?php
	session_start();
	if(!isset($_SESSION["jara_admin"])) {
		header("Location: ../login.php");
		exit;
	}
	if($_SESSION["jara_permissions"][2] == 0) {	
		header("Location: error.php");
		exit;
	}
	require_once("../include/templating_fns.php");
	require_once("../include/db_fns.php");
	require_once("../include/auth_fns.php");
	jara_page_start("Add User - Administrator CP");
	if(isset($_POST["user_action"])) {
		try {
			$username = $_POST["username"];
			$password = $_POST["password"];
			if(!get_magic_quotes_gpc()) {
				$username = addslashes($username);
				$password = addslashes($password);
			}
			$p1 = ((isset($_POST["permission_posts"])) ? 1 : 0);
			$p2 = ((isset($_POST["permission_pages"])) ? 1 : 0);
			$p3 = ((isset($_POST["permission_users"])) ? 1 : 0);
			$p4 = ((isset($_POST["permission_upload"])) ? 1: 0);
			$permissions = array($p1, $p2, $p3, $p4);
			$result = jara_user_create($username, $password, $permissions);
			if($result == false) {
				throw new JaraGeneralException("Could not create the user $username.");
			}
			else {
				echo "<p>The user <strong>$username</strong> has been created with the password <strong>$password</strong>.</p>";
				jara_page_end();
				exit;
			}
		}
		catch(JaraDatabaseException $ex) {
?>
	<p>
		A database error occured during the process of creating this page.
	</p>
	<p>
		Error type: <?php echo (($ex->getSqlStage() == 1) ? "MySQL connection error" : "MySQL query error"); ?><br />
		Error message: &quot;<?php echo $ex->getSqlMsg(); ?>&quot; [code <?php echo $ex->getSqlCode(); ?>]
	</p>
<?php
			jara_page_end();
		}
		catch(JaraGeneralException $ex) {
?>
	<p>
		A general error occured during the process of creating this page.
	</p>
	<p>
		Error message: &quot;<?php echo $ex->getMessage(); ?>&quot;
	</p>
<?php
			jara_page_end();
		}
		exit;
	}
?>
<form action="add_user.php" method="post">
<h3>User details</h3>
<p>
<input type="hidden" name="user_action" id="user_action" value="create" />
New username: <input type="text" id="username" name="username" width="20" /><br />
New password: <input type="password" id="password" name="password" width="20" /><br />
</p>
<h3>Permissions</h3>
<p>
<input type="checkbox" name="permission_posts" id="permission_posts" checked="checked" /> Allow access to post-related data<br />
<input type="checkbox" name="permission_pages" id="permission_pages" checked="checked" /> Allow access to page-related data<br />
<input type="checkbox" name="permission_users" id="permission_users" /> Allow access to user-related data<br />
<input type="checkbox" name="permission_posts" id="permission_upload" checked="checked" /> Allow access to upload-related data
</p>
<p>
<input type="submit" value="Add user" />
</p>
</form>
<?php
	jara_page_end();
?>